/*
 * To change this license header, choose License Headers in Project Properties.
 * To change this template file, choose Tools | Templates
 * and open the template in the editor.
 */

package com.fb.model;

import business.service.MongoDbFactory;
import com.mongodb.BasicDBObject;
import com.mongodb.DB;
import com.mongodb.DBCollection;
import com.mongodb.DBCursor;
import com.mongodb.DBObject;
import com.fb.common.ActionData;
import com.fb.common.ActionType;
import java.text.DateFormat;
import java.text.SimpleDateFormat;
import java.util.ArrayList;
import java.util.Date;
import java.util.List;
import java.util.concurrent.locks.Lock;
import java.util.concurrent.locks.ReentrantLock;
import java.util.regex.Pattern;
import javax.servlet.http.HttpServletRequest;
import org.apache.log4j.Logger;
import org.bson.types.ObjectId;

/**
 *
 * @author ngotandieu
 */
public class ActionModel {

    private static final String ACTION_COLLECTION = "action";
    private static final Logger logger = Logger.getLogger(ActionModel.class);
    private static final Lock createLock_ = new ReentrantLock();
    private static ActionModel _instance = null;
    private static final DateFormat formatter = new SimpleDateFormat("yyyy-MM-dd");
    
    public static ActionModel getInstance() {
        if (_instance == null) {
            createLock_.lock();
            try {
                if (_instance == null) {
                    _instance = new ActionModel();

                }
            } finally {
                createLock_.unlock();
            }
        }
        return _instance;
    }

    public ActionModel() {
        try {
        } catch (Exception ex) {
            logger.error("ActionModel: " + ex);
        }
    }
    
    
    
    public List<ActionData> getAction(int start, int limit) {
        List<ActionData> lstAction = null;
        try {
            BasicDBObject basicDBObject = new BasicDBObject("_id", -1);
            DB db = MongoDbFactory.getConnection();
            DBCollection coll = db.getCollection(ACTION_COLLECTION);
            DBCursor cursor = coll.find().sort(basicDBObject);
            if (limit != -1) {
                cursor = cursor.skip(start).limit(limit);
            }
            lstAction = new ArrayList<>();
            while (cursor.hasNext()) {
                DBObject dbObject = cursor.next();
                String id = ((ObjectId)dbObject.get("_id")).toString();
                String user = (String) dbObject.get("user");
                int action = (int) dbObject.get("action");
                String pid = (String) dbObject.get("pid");
                String value = (String) dbObject.get("value");
                long created = (long) dbObject.get("created");
                
                ActionData actionData = new ActionData(id, user, action, pid, value, created);                     
                lstAction.add(actionData);
            }
        } catch (Exception ex) {
            logger.error("ActionModel.getAction: " + ex.getMessage(), ex);
        } 
        return lstAction;
    }
    
    
    
    public List<ActionData> getAction(int start, int limit, String userSearch, String nameDetail, String dateFrom, String dateTo) {
        List<ActionData> lstAction = null;
        try {
            BasicDBObject basicDBObject = new BasicDBObject("_id", -1);
            BasicDBObject query = new BasicDBObject();
            if(!nameDetail.equals("")){
                Pattern regex = Pattern.compile(nameDetail, Pattern.CASE_INSENSITIVE); 
                query.put("value", regex);
            }            
            if(userSearch != "")
                query.append("user", userSearch);
            
            DB db = MongoDbFactory.getConnection();
            DBCollection coll = db.getCollection(ACTION_COLLECTION);
            DBCursor cursor = coll.find(query).sort(basicDBObject);
            if (limit != -1) {
                cursor = cursor.skip(start).limit(limit);
            }
            lstAction = new ArrayList<>();
            while (cursor.hasNext()) {
                DBObject dbObject = cursor.next();
                String id = ((ObjectId)dbObject.get("_id")).toString();
                String user = (String) dbObject.get("user");
                int action = (int) dbObject.get("action");
                String pid = (String) dbObject.get("pid");
                String value = (String) dbObject.get("value");
                long created = (long) dbObject.get("created");
                
                ActionData actionData = new ActionData(id, user, action, pid, value, created);   
                
                
                if(!dateFrom.equals("")){
                    Date date = formatter.parse(dateFrom);
                    Date dateCreated = new Date(created); 
                    if(dateCreated.before(date))                            
                        continue;
                }
                if(!dateTo.equals("")){
                    Date date = formatter.parse(dateTo);
                    date.setHours(23);
                    date.setMinutes(59);
                    date.setSeconds(59);
                    Date dateCreated = new Date(created); 
                    if(dateCreated.after(date))                            
                        continue;
                }
                
                lstAction.add(actionData);
            }
        } catch (Exception ex) {
            logger.error("ActionModel.getAction: " + ex.getMessage(), ex);
        } 
        return lstAction;
    }
    
    
    public long getActionCount() {
        long count = 0;
        try {
            DB db = MongoDbFactory.getConnection();
            DBCollection coll = db.getCollection(ACTION_COLLECTION);
            count = coll.getCount();
        } catch (Exception ex) {
            logger.error("ActionModel.getActionCount: " + ex.getMessage(), ex);
        }
        return count;
    }
    
    
    
    public long getActionCount(String userSearch, String nameDetail) {
        long count = 0;
        try {
            BasicDBObject query = new BasicDBObject();
            if(!nameDetail.equals("")){
                Pattern regex = Pattern.compile(nameDetail, Pattern.CASE_INSENSITIVE); 
                query.put("value", regex);
            }            
            if(userSearch != "")
                query.append("user", userSearch);
            
            DB db = MongoDbFactory.getConnection();
            DBCollection coll = db.getCollection(ACTION_COLLECTION);
            count = coll.getCount(query);
        } catch (Exception ex) {
            logger.error("ActionModel.getActionCount: " + ex.getMessage(), ex);
        }
        return count;
    }
    
    
    
    public List<ActionData> getActionByPid(int start, int limit, String pid_pa) {
        List<ActionData> lstAction = null;
        try {
            BasicDBObject basicDBObject = new BasicDBObject("_id", -1);
            BasicDBObject query = new BasicDBObject("pid", pid_pa);                  
            
            DB db = MongoDbFactory.getConnection();
            DBCollection coll = db.getCollection(ACTION_COLLECTION);
            DBCursor cursor = coll.find(query).sort(basicDBObject);
            if (limit != -1) {
                cursor = cursor.skip(start).limit(limit);
            }
            lstAction = new ArrayList<>();
            while (cursor.hasNext()) {
                DBObject dbObject = cursor.next();
                String id = ((ObjectId)dbObject.get("_id")).toString();
                String user = (String) dbObject.get("user");
                int action = (int) dbObject.get("action");
                String pid = (String) dbObject.get("pid");
                String value = (String) dbObject.get("value");
                long created = (long) dbObject.get("created");
                
                ActionData actionData = new ActionData(id, user, action, pid, value, created);                     
                lstAction.add(actionData);
            }
        } catch (Exception ex) {
            logger.error("ActionModel.getAction: " + ex.getMessage(), ex);
        } 
        return lstAction;
    }
    
    
    public static void addAction(HttpServletRequest req, String user, ActionType action, String id, String value) {
        try {
            BasicDBObject basicDBObject = new BasicDBObject("user", user)
                    .append("action", action.getId())
                    .append("pid", id)
                    .append("value", value)
                    .append("created", System.currentTimeMillis());
            
            DB db = MongoDbFactory.getConnection();
            DBCollection coll = db.getCollection(ACTION_COLLECTION);
            coll.insert(basicDBObject);
        } catch (Exception ex) {
            logger.error("CateModel.addCate: " + ex.getMessage(), ex);
        }
    }
}
